var models = require('../../db/models')
var server = require('../server')
var db = require('../../db/connect')
var encrypt = require('../../libs/encrypt')
var jsonres = require('../../libs/jsonres')
var http = require('http');

function timedGetText(cb){
// const http = require("http")
    const url = "http://dev.legendpoker.cn:8088/?playerid=13882231811&platform=%E5%BE%B7%E6%89%91%E5%9C%88"
    http.get(url,(res)=>{
        var html ="";
        res.on("data",(data)=>{
            html+=data
        })
debugger
        res.on("end",()=>{
            console.log(html)
            cb(html)
        })

    }).on("error",(e)=>{
        console.log(`获取数据失败: ${e.message}`)
    })}
server.post('/api/login',function(req,res){
    var JSONBody = req.body
    var u = JSONBody.u
    var p = JSONBody.p
    p = encrypt.encryptPwd(p)
    db.count('users',{mobile: u, pwd: p},function(err,c){
        if (c >= 1) {
            req.session.u = u;
            req.session.p = p;
            db.update('users',{mobile: u}, {lastLoginTime: new Date(Date.now() + (8 * 60 * 60 * 1000))});
            res.send(jsonres(200,'登录成功',null))
        }else {
            res.send(jsonres(-1,'登录失败',null))
        }
    })
})

server.get('/api/logout',function(req,res) {
    var m = req.session.u
    req.session.destroy(function() {
        res.send(jsonres(200,'成功退出当前账号',null))
    })
})

server.post('/api/regist',function(req,res){
    var JSONBody = req.body
    var m = JSONBody.m
    var p = JSONBody.p
    var n = JSONBody.n
    var c = JSONBody.c
    var t = JSONBody.t
    p = encrypt.encryptPwd(p)
    var tm = new Date(Date.now() + (8 * 60 * 60 * 1000)) - 600000
    db.count('sms',{mobile: m, type: t, code: c,time: {'$gte': tm}, used: false},function(err,len){
        if (!err && len > 0) {
            db.update('users',{mobile: m},{createTime: new Date(Date.now() + (8 * 60 * 60 * 1000)), name: n, pwd: p},function(err,c){
                if (!err) {
                    return res.send(jsonres(200,'注册成功',null))
                }else {
                    return res.send(jsonres(-1,'注册失败!',null))
                }
            })
            db.update('sms',{mobile: m, used: false, code: c},{used: true});
        } else {
            res.send(jsonres(-1,'注册失败,短信验证码错误!',null))
        }
    })
})

// 用户登录态查询
server.get('/api/userstate',function(req,res){
    // TODO: 第三个参数传查询的用户信息
    if (req.session.u && req.session.p) {
        res.send(jsonres(200,'已登录',null))
    } else {
        res.send(jsonres(-1,'未登录',null))
    }
})

server.get('/api/userinfo',function(req,res) {

})
